package ia.robot.graphics;

import java.awt.image.BufferedImage;
import java.awt.image.DataBufferInt;
import java.io.File;

import javax.imageio.ImageIO;
import javax.swing.ImageIcon;

/**
 * Class that holds textures to draw onto a JCanvas.
 * 
 * @author Jaime A. Corrales Gonzalez
 */
public class Textures {
	public static Bitmap tiles = loadBitmap("./textures/tiles.png");

	public static final int TILE_WIDTH = 32;
	public static final int TILE_HEIGHT = 32;

	public static final int TILE_GRASS = 0x0;
	public static final int TILE_STONE = 0x1;

	public static final int TILE_BOT_NORTH = 0x8;
	public static final int TILE_BOT_EAST = 0x9;
	public static final int TILE_BOT_SOUTH = 0xA;
	public static final int TILE_BOT_WEST = 0xB;

	public static final int TILE_GOAL = 0xC;

	/**
	 * Creates a Bitmap based off a tile from a texture.
	 * 
	 * @param tile
	 *            - Tile to process.
	 * @return Bitmap created.
	 */
	public static Bitmap getBitmap(int tile) {
		Bitmap b = new Bitmap(TILE_WIDTH, TILE_HEIGHT);

		int x = tile % 0x4;
		int y = tile / 0x4;

		b.draw(tiles, 0, 0, x * TILE_WIDTH, y * TILE_HEIGHT, TILE_WIDTH,
				TILE_HEIGHT);

		return b;
	}

	/**
	 * Creates an icon for buttons based off a tile from a texture.
	 * 
	 * @param tile
	 *            - Tile to process.
	 * @return Icon created.
	 */
	public static ImageIcon getIcon(int tile) {
		BufferedImage img = new BufferedImage(TILE_WIDTH, TILE_HEIGHT,
				BufferedImage.TYPE_INT_ARGB);
		int[] pixels = ((DataBufferInt) img.getRaster().getDataBuffer())
				.getData();

		Bitmap b = getBitmap(tile);

		for (int i = 0; i < b.getNumPixels(); i++)
			pixels[i] = b.getPixel(i);

		ImageIcon icon = new ImageIcon(img);

		return icon;
	}

	/**
	 * Loads a texture file onto a Bitmap.
	 * 
	 * @param fileName
	 *            - Name of the file to load.
	 * @return Bitmap loaded.
	 */
	private static Bitmap loadBitmap(String fileName) {
		try {
			BufferedImage img = ImageIO.read(new File(fileName));

			int width = img.getWidth();
			int height = img.getHeight();

			Bitmap result = new Bitmap(width, height);

			img.getRGB(0, 0, width, height, result.getPixels(), 0, width);

			for (int i = 0; i < result.getNumPixels(); i++) {
				int col = result.getPixel(i);

				if (col == 0xFFFF00FF)
					col = 0;

				result.setPixel(i, col);
			}

			return result;
		} catch (Exception e) {
			System.err
					.println("Error - Couldn't load graphic resources. Aborting...");

			System.exit(1);
		}

		return null;
	}
}
